import { defineComponent, reactive, createVNode, onMounted, ref } from "vue";
import Page from "@/components/public/page/page";
import LForm, { LFormItem } from "@/components/public/lForm/lForm";
import { CardWithTitle } from "@/components/public/card/card";
import styles from "./groupOrderEntryImportPage.module.less";
import useNavigator from "@/hooks/useNavigator";
import { Modal, message, UploadProps, Progress, Spin } from "ant-design-vue";
import { $getSearchCountryList } from "@/api/search/search";
import {
  DoubleRightOutlined,
  CheckOutlined,
  InboxOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import {
  $groupOrderAdd,
  $getGroup,
  $groupOrderImport,
  $groupOrderValidate,
  $groupOrderCreate,
  $groupOrderCreateFaliedTask,
  $groupOrderCreateFaliedPeople,
  $groupOrdeInsured2023List
} from "@/api/groupOrder/groupOrder";
import { $getAreaList } from "@/api/common/common";
import eventBus from "@/common/mitt";
import validateInstance from "@/libs/validate/validate";
import useXlsx from "@/hooks/useXlsx";
export default defineComponent({
  name: "groupOrderEntryImportPage",
  setup() {
    const navigator = useNavigator();
    const xlsx = useXlsx();
    const title = ref("" as any);
    const state = reactive({
      nextIndex: 0,
      listTitle: ["基础信息", "上传清单", "上传清单", "上传清单"],
      fileList: [],
      citylist: [],
      arealist: [],
      number: "",
      fileName: "",
      datalist: [],
      countrylist: [],
      nextBool: false,
      loading: false,
      form: {
        applicant_mobile: "", //手机号
        contact_name: "", //姓名
        country_id: undefined,
      },
      columns: [
        {
          title: "续保/终保",
          dataIndex: ["is_new", "label"],
          key: "is_new",
          align: "center",
        },
        {
          title: "被保人姓名",
          dataIndex: "name",
          key: "name",
          align: "center",
        },
        {
          title: "证件类型",
          dataIndex: ["id_type", "label"],
          key: "id_type",
          align: "center",
        },
        {
          title: "证件号码",
          dataIndex: "id_no",
          key: "id_no",
          align: "center",
        },
        {
          title: "出生日期",
          dataIndex: "birthday",
          key: "birthday",
          align: "center",
        },
        {
          title: "性别",
          dataIndex: ["sex", "label"],
          key: "sex",
          align: "center",
        },
        {
          title: "手机号",
          dataIndex: "mobile",
          key: "mobile",
          align: "center",
        },
        {
          title: "所在市",
          dataIndex: ["city_id", "label"],
          key: "city_id",
          align: "center",
        },
        {
          title: "所在区县",
          dataIndex: ["area_id", "label"],
          key: "area_id",
          align: "center",
        },
        {
          title: "所在乡镇/街道",
          dataIndex: ["street_id", "label"],
          key: "street_id",
          align: "center",
        },
        {
          title: "所在村/社区",
          dataIndex: ["village_id", "label"],
          key: "village_id",
          align: "center",
        },
        {
          title: "商保/低保",
          dataIndex: ["people_type", "label"],
          align: "center",
          width: "180px",
        },
        {
          title: "生效时间",
          dataIndex: "start_date",
          key: "start_date",
          align: "center",
        },
        {
          title: "上传时间",
          dataIndex: "upload_date",
          key: "upload_date",
          align: "center",
        },
        {
          title: "处理结果",
          dataIndex: "status",
          key: "status",
          align: "center",
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
          align: "center",
        },
      ],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
    } as any);
    onMounted(() => {
      //获取城市
      $getAreaList({}).then((res: any) => {
        res.data.forEach((item: any) => {
          if (item.id == state.form.province_id) {
            state.citylist = item.child.map((x: any) => {
              return {
                value: x.id,
                label: x.name,
                list: x.child,
              };
            });
          }
        });
      });
    })
    const cancelHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
        navigator.back();
      } else if (state.nextIndex == 1) {
        state.nextIndex = 0;
      } else if (state.nextIndex == 2) {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "若返回上一步,需要重新上传文件,成功上传的内容将不会被保存",
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            state.fileList = [];
            state.fileName = "";
            state.nextIndex = 1;
            state.nextBool = false;
          },
        });
      } else if (state.nextIndex == 3) {
        eventBus.groupOrderEntryImportConfirm.emit();
        navigator.back();
      }
    };
    var hide: any;
    const confirmHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
        if (validateInstance.test(state.form.applicant_mobile, "phone") == false) {
          message.error("填写手机号有误");
          return;
        }
        $groupOrderAdd(state.form).then((res: any) => {
          state.number = res.data?.number || "";
          state.nextIndex = 1;
        }).finally(() => {
          state.loading = false;
        })
      } else if (state.nextIndex == 1) {
        state.nextBool = false;
        uploadFile();
      } else if (state.nextIndex == 2) {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content:
            "处理结果为“异常“情况时仍会录入.",
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            state.loading = true;
            hide = message.loading('导入中', 0);
            // $groupOrderCreate({ number: state.number }).then((res: any) => {
            // }).catch(() => {
            //   setTimeout(hide);
            // });
            searchResult();
          },
        });
      }
    };
    const searchResult = () => {
      $groupOrderCreate({ number: state.number }).then((res: any) => {
        if (res?.data?.status == 10) {
          searchResult();
        }
        else if (res?.data?.status == -1) {
          state.loading = false;
          setTimeout(hide);
          message.error("导入失败,请联系技术人员");
        }
        else if (res?.data?.status == 1) {
          state.loading = false;
          setTimeout(hide);
          message.success("导入成功");
          state.nextIndex = 3;
          if (res?.data?.download == true) {
            Modal.confirm({
              title: "提示",
              icon: createVNode(ExclamationCircleOutlined),
              content:
                "有部分信息未导入,是否下载重新导入",
              okText: "确认",
              cancelText: "取消",
              onCancel: () => {
                eventBus.groupOrderEntryImportConfirm.emit();
                navigator.back();
              },
              onOk: () => {
                $groupOrderCreateFaliedTask({
                  number: state.number
                }).then((taskRes: any) => {
                  const interval = setInterval(() => {
                    const stopInterval = () => {
                      clearInterval(interval);
                    }
                    $groupOrderCreateFaliedPeople({
                      import_number: state.number,
                      number: taskRes.data?.number,
                    }).then((peopleRes: any) => {
                      if (peopleRes.data.status === 1) {
                        window.open(peopleRes.data.url);
                        state.fileList = [];
                        state.fileName = "";
                        state.nextIndex = 0;
                        stopInterval();
                      } else if (peopleRes.data.status === -1) {
                        eventBus.groupOrderEntryImportConfirm.emit();
                        navigator.back();
                        stopInterval();
                      }
                    }).catch(() => {
                      eventBus.groupOrderEntryImportConfirm.emit();
                      navigator.back();
                      stopInterval();
                    })
                  }, 1000)
                }).catch(() => {
                  eventBus.groupOrderEntryImportConfirm.emit();
                  navigator.back();
                })
              },
            });
          }
        }
      }).catch(() => {
        setTimeout(hide);
      }).finally(() => {
        state.loading = false;
      })
    }
    //上传文件
    const uploadFile = () => {
      let hide = message.loading("录入团单中......")
      state.loading = true;
      const formData: FormData = new FormData();
      formData.set("file", state.fileList[0].originFileObj);
      $groupOrderImport(
        { number: state.number },
        { file: state.fileList[0].originFileObj }
      ).then((res: any) => {
        state.nextIndex = 2;
        state.loading = false;
        setTimeout(hide);
        $groupOrderValidate({
          page: 1,
          limit: 10,
          number: state.number,
        }).then((res: any) => {
          state.pagination.total = res.data?.total;
          state.pagination.current = res.data?.current_page;
          state.pagination.pageSize = res.data?.per_page;
          state.datalist = res.data?.data || [];
          if (res.data?.data[0].status.label === "失败") {
            state.nextBool = true;

          }
        });
      });
    };
    //基础信息
    const BasicInformation = () => (
      <LForm v-model={state.form}>
        {/* <LFormItem label="投保单位名称" prop="">
          <a-input
            v-model:value={state.form.applicant_name}
            placeholder="请输入单位名称"
          ></a-input>
        </LFormItem>
        <LFormItem label="投保单位证件号" prop="">
          <a-input
            v-model:value={state.form.applicant_id_no}
            placeholder="请输入单位证件号"
          ></a-input>
        </LFormItem>
        <LFormItem label="投保单位地址" prop="">
          <a-input
            v-model:value={state.form.address}
            placeholder="请输入单位地址"
          ></a-input>
        </LFormItem> */}
        <LFormItem label="所在村/社区" prop="">
          <a-select
            v-model:value={state.form.country_id}
            options={state.countrylist}
            placeholder="请选择所在村/社区"
            style="width:100%"
            onChange={(e: any, option: any) => {
            }}
          ></a-select>
        </LFormItem>
        <LFormItem label="联系人姓名" prop="">
          <a-input
            v-model:value={state.form.contact_name}
            placeholder="请输入联系人姓名"
          ></a-input>
        </LFormItem>
        <LFormItem label="联系人手机号" prop="">
          <a-input
            v-model:value={state.form.applicant_mobile}
            placeholder="请输入联系人手机号"
          ></a-input>
        </LFormItem>
        {/* <LFormItem label="所在市" prop="">
          <a-select
            v-model:value={state.form.city_id}
            options={state.citylist}
            placeholder="请选择所在市"
            style="width:100%"
            onChange={(e: any, option: any) => {
              state.form.area_id = undefined;
              state.arealist = option.list.map((x: any) => {
                return {
                  value: x.id,
                  label: x.name,
                };
              });
            }}
          ></a-select>
        </LFormItem>
        <LFormItem label="所在区/县" prop="">
          <a-select
            v-model:value={state.form.area_id}
            options={state.arealist}
            placeholder="请选择所在区/县"
            style="width:100%"
          ></a-select>
        </LFormItem> */}
      </LForm>
    );
    //手动上传
    const beforeUpload: UploadProps["beforeUpload"] = (file) => {
      state.fileName = file.name;
      state.fileList = [file];
      return false;
    };
    //上传清单
    const UploadChecklist = () => (
      <div class={styles.uploadChecklist_box}>
        <div class={styles.head_box}>
          <div class={styles.head_left_box}>
            {state.nextIndex > 1 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                  state.nextIndex < 1 && styles.numberOne_current_box,
                ]}
              >
                1
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>导入清单文件</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            {state.nextIndex > 2 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                  state.nextIndex < 2 && styles.numberOne_current_box,
                ]}
              >
                2
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>确认上传结果</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            <div
              class={[
                styles.numberOne_box,
                state.nextIndex < 3 && styles.numberOne_current_box,
              ]}
            >
              3
            </div>
            <div class={styles.content_box}>
              <div class={styles.label_box}>上传成功</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
        </div>
        <div class={styles.body_box}>
          {state.nextIndex == 1 && (
            <div class={styles.content_box}>
              <div class={styles.content_head_box}>
                <a-button
                  type="primary"
                  size="small"
                  onClick={() => {
                    $getGroup({}).then((res: any) => {
                      window.open(res.data.url);
                    });
                  }}
                >
                  下载空白模版
                </a-button>
                <a-button
                  type="primary"
                  size="small"
                  style={{ marginLeft: "20px" }}
                  loading={xlsx.state.running == "doing"}
                  onClick={async () => {
                    title.value = "正在导出文件...";
                    xlsx.init({
                      limit: 2000,
                      otherParams: {},
                      service: $groupOrdeInsured2023List,
                    })
                    await xlsx.defineList([
                      {
                        label: '姓名',
                        value: 'name',
                        width: 25,
                      },
                      {
                        label: '证件号',
                        value: 'id_no',
                        width: 25,
                      },
                      {
                        label: '手机号',
                        value: 'mobile',
                        width: 20,
                      },
                      {
                        label: '生效日期',
                        value: "people_start_date",
                        width: 25,
                      },
                      {
                        label: '城市',
                        value: "city",
                        width: 20,
                      },
                      {
                        label: '区/县',
                        value: "area",
                        width: 20,
                      },
                      {
                        label: '街道',
                        value: "street",
                        width: 25,
                      },
                      {
                        label: '村/社区',
                        value: "village",
                        width: 25,
                      },
                      {
                        label: '承保日期',
                        value: "insure_time",
                        width: 20,
                      },
                    ]);
                    await xlsx.exportToExcel('2023年承保人员.xlsx');
                  }}
                >
                  下载去年商保承保人员
                </a-button>
                <div class={styles.content_label_box}>点击下载团单模版</div>
              </div>
              <div class={styles.uploadBox}>
                <a-upload-dragger
                  v-model:fileList={state.fileList}
                  name="file"
                  before-upload={beforeUpload}
                  showUploadList={false}
                >
                  <p class="ant-upload-drag-icon">
                    <InboxOutlined></InboxOutlined>
                  </p>
                  {state.fileName ? (
                    <p class="ant-upload-text">{state.fileName}</p>
                  ) : (
                    <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                  )}
                </a-upload-dragger>
              </div>
            </div>
          )}
          {state.nextIndex > 1 && (
            <div class={styles.group_box}>
              {state.nextIndex == 3 && (
                <div class={styles.group_order_box}>
                  <div class={styles.group_order_round_box}>
                    <CheckOutlined />
                  </div>
                  <div class={styles.group_order_label_box}>团单添加成功</div>
                </div>
              )}
              <Grouplist />
            </div>
          )}
        </div>
      </div>
    );
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      state.pagination.current = pag.current;
      state.pagination.pageSize = pag.pageSize;
      $groupOrderValidate({
        page: state.pagination.current,
        limit: state.pagination.pageSize,
        number: state.number,
      }).then((res: any) => {
        state.pagination.total = res.data?.total;
        state.datalist = res.data?.data || [];
      });
    };
    //上传团单列表结果
    const Grouplist = () => (
      <div style={{ width: "100%" }}>
        <a-table
          dataSource={state.datalist}
          columns={state.columns}
          pagination={state.pagination}
          scroll={{ x: 2000 }}
          onChange={tableChangeHandler}
          v-slots={{
            bodyCell: ({ column, record }: any) => {
              if (column.dataIndex == "status") {
                if (record.status.value == "1") {
                  return (
                    <div style={{ color: "green" }}>{record.status.label}</div>
                  );
                } else {
                  return (
                    <div style={{ color: "red" }}>{record.status.label}</div>
                  );
                }
              }
            },
          }}
        />
      </div>
    );
    onMounted(() => {
      $getSearchCountryList({}).then((res: any) => {
        state.countrylist = res.data;
      })
    })
    return () => (
      <Page>
        <CardWithTitle title="录入团单">
          <div class={styles.orderEntryAdd}>
            {state.nextIndex == 0 && <BasicInformation />}
            {state.nextIndex > 0 && <UploadChecklist />}
            <div class={styles.btn_Box}>
              <a-button
                size="small"
                style={{ width: "55px" }}
                onClick={() => cancelHandler()}
              >
                {state.nextIndex == 3
                  ? "关闭"
                  : state.nextIndex == 0
                    ? "返回"
                    : "上一步"}
              </a-button>
              {state.nextIndex != 3 && (
                <div class={styles.right_btn_box}>
                  <a-button
                    type="primary"
                    size="small"
                    loading={state.loading}
                    disabled={state.nextBool}
                    onClick={() => confirmHandler()}
                  >
                    下一步
                  </a-button>
                </div>
              )}
            </div>
          </div>
        </CardWithTitle>
        {
          <Modal
            title={title.value}
            visible={['doing'].includes(xlsx.state.running)}
            closable={false}
            footer={null}
          >
            <div class={styles["progress_box"]}>
              {
                xlsx.state.running === "doing" && xlsx.progress.value < 100 && (
                  <Progress type="circle" percent={xlsx.progress.value} />
                )
              }
              {
                xlsx.state.running === "doing" && xlsx.progress.value === 100 && (
                  <Spin tip="正在导出文件,请勿关闭当前页面..." size="large" />
                )
              }
            </div>
          </Modal>
        }
      </Page>
    )
  }
})